package cn.information.view.extend;

import cn.information.bean.Product;
import cn.information.dao.ProductDao;

import javax.swing.*;
import java.awt.*;
import java.util.List;

public class ProductTypeUI extends JFrame {
    private JComboBox<String> typeComboBox;
    private JButton btnConfirm;

    public ProductTypeUI() {
        setTitle("添加商品信息");
        setSize(400, 200);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout());

        JPanel panelCenter = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 20));
        JPanel panelSouth = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));

        // 获取所有商品类型
        ProductDao productDao = new ProductDao();
        List<Product> products = productDao.findAll();
        String[] types = products.stream()
                .map(Product::getSptype)
                .distinct()
                .toArray(String[]::new);

        panelCenter.add(new JLabel("请选择商品:"));
        typeComboBox = new JComboBox<>(types);
        panelCenter.add(typeComboBox);

        btnConfirm = new JButton("确认");
        btnConfirm.setEnabled(false); // Initially disabled
        panelSouth.add(btnConfirm);

        JButton btnCancel = new JButton("取消");
        btnCancel.addActionListener(e -> dispose());
        panelSouth.add(btnCancel);

        add(panelCenter, BorderLayout.CENTER);
        add(panelSouth, BorderLayout.SOUTH);

        // Add listener to combo box
        typeComboBox.addActionListener(e -> {
            if (typeComboBox.getSelectedIndex() >= 0) {
                btnConfirm.setEnabled(true);
            } else {
                btnConfirm.setEnabled(false);
            }
        });

        // Add listener to confirm button
        btnConfirm.addActionListener(e -> {
            String selectedType = (String) typeComboBox.getSelectedItem();
            new ProductTypeputUI(selectedType).setVisible(true);
            dispose();
        });

        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new ProductTypeUI().setVisible(true);
        });
    }
}
